package com.sgb.kjwl.view.ui.activity.manage

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityWebsiteAnnouncementListBinding
import com.sgb.kjwl.databinding.ItemAnnouncementManagementBinding
import com.sgb.kjwl.model.entity.manage.AnnouncementListEntity
import com.sgb.kjwl.view.ui.activity.self.websiteManage.WebsiteBulletinUploadActivity
import com.sgb.kjwl.viewmodel.manage.WebsiteAnnouncementListViewModel
import com.swgk.core.BaseAppHelper
import com.swgk.core.dialog.RoundCornerDialog
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.swgk.core.util.MToast

/**
 * 公告管理activity
 */

class WebsiteAnnouncementManagementActivity : AppActivity() {

    private lateinit var mViewModel : WebsiteAnnouncementListViewModel

    private lateinit var mBinding : ActivityWebsiteAnnouncementListBinding

    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    private lateinit var mAdapter : AnnouncementManagementAdapter

    companion object{
        fun launch(context: Context){
            val intent = Intent()
            intent.setClass(context, WebsiteAnnouncementManagementActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initView() {
        super.initView()
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_website_announcement_list)
        mViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(BaseAppHelper.get().instance).create(
            WebsiteAnnouncementListViewModel::class.java)
        mBinding.include.titleView.text = "公告管理"
        mBinding.include.ivBack.setOnClickListener { finish() }
        mBinding.include.rightView.text = "发布"
        mBinding.include.rightView.setOnClickListener {
            val intent = Intent(this, WebsiteBulletinUploadActivity::class.java)
            startActivity.launch(intent)
        }
        initRecyclerView()
        mViewModel.mDeletePosition.observe(this, {
            if (it == -1){
                MToast.showToast(this, "删除失败")
            } else {
                MToast.showToast(this, "删除成功")
                mAdapter.remove(it)
            }
        })
        mViewModel.mManagementList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (it != null){
                if(isLoadMore){
                    mAdapter.addData(it)
                } else {
                    mAdapter.setNewData(it)
                }
            }
        })
    }

    override fun init() {
        super.init()
        isLoadMore = false
        mViewModel.getAnnouncementManagement(isLoadMore)
    }

    private fun initRecyclerView() {
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                mViewModel.getAnnouncementManagement(isLoadMore)
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                mViewModel.getAnnouncementManagement(isLoadMore)
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinding.recycleView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        mBinding.recycleView.setItemViewCacheSize(100)
        mBinding.recycleView.setHasFixedSize(true)
        mAdapter = AnnouncementManagementAdapter(this, R.layout.item_announcement_management)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp1), resources.getColor(R.color.color_line)
            )
        )
        mAdapter.setCallBack(object : ClickCallback{

            override fun deleteItem(item: AnnouncementListEntity?, position: Int) {
                // TODO: 2021/11/30 删除 操作
                if (item != null){
                    showDialog("确认删除吗", item.no, position)
                }
            }

            override fun clickItem(item: AnnouncementListEntity?, position: Int) {
                // TODO: 2021/11/30 详情
                if (item != null){
                    mViewModel.getH5Url(this@WebsiteAnnouncementManagementActivity, item.no, "announcementDetail")
                }
            }

        })

    }



    class AnnouncementManagementAdapter(mContext : Context, layoutResId : Int) : BaseQuickAdapter<AnnouncementListEntity, BaseViewHolder>(layoutResId){
        private var mItemBinding : ItemAnnouncementManagementBinding ?= null

        private var mColorSpan : ForegroundColorSpan = ForegroundColorSpan(mContext.resources.getColor(R.color.color_title_medium))

        private var ssb : SpannableStringBuilder ?= null

        private var mCallback : ClickCallback ?= null

        fun setCallBack(callback : ClickCallback){
            this.mCallback = callback
        }

        override fun convert(helper: BaseViewHolder?, item: AnnouncementListEntity?) {
             mItemBinding = DataBindingUtil.bind(helper!!.itemView)
             if (mItemBinding != null){
                 mItemBinding!!.entity = item
                 setColorSpan(mContext.resources.getString(R.string.announcement_publish_person, item!!.createUserName), mItemBinding!!.tvPublish)
                 mItemBinding!!.tvDelete.setOnClickListener {
                     if (mCallback != null){
                         mCallback!!.deleteItem(item, helper.layoutPosition)
                     }
                 }
                 mItemBinding!!.root.setOnClickListener {
                     if (mCallback != null){
                         mCallback!!.clickItem(item, helper.layoutPosition)
                     }
                 }
                 mItemBinding!!.tvType.text = item.typeName
                 when (item.type) {
                     1 -> {//商品
                        mItemBinding!!.tvType.setColors(R.color.color_secondary_red_third, R.color.color_secondary_red_four)
                     }
                     2 -> {//招采
                         mItemBinding!!.tvType.setColors(R.color.color_secondary_orange_ninth, R.color.color_secondary_orange_fifth)
                     }
                     3 -> {//集采
                         mItemBinding!!.tvType.setColors(R.color.color_secondary_purple_four, R.color.color_secondary_purple_fifth)
                     }
                     4 -> {//租赁
                         mItemBinding!!.tvType.setColors(R.color.color_secondary_yellow_fifth, R.color.color_secondary_yellow_four)
                     }
                     5 -> {//物流
                         mItemBinding!!.tvType.setColors(R.color.color_third_green_easy, R.color.color_secondary_green_easy_six)
                     }
                     6 -> {//工程
                         mItemBinding!!.tvType.setColors(R.color.color_secondary_blue_four, R.color.color_secondary_blue_third)
                     }
                     7 -> {//企服
                         mItemBinding!!.tvType.setColors(R.color.color_secondary_brown, R.color.color_secondary_brown_third)
                     }
                     8 -> {//商品
                         mItemBinding!!.tvType.setColors(R.color.color_secondary_grey, R.color.color_secondary_grey_third)
                     }
                 }
             }
        }

        private fun setColorSpan(content: String, tv: TextView) {
            ssb = SpannableStringBuilder(content)
            ssb!!.setSpan(mColorSpan, content.indexOf(": "), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }

    }


    interface ClickCallback{
        fun deleteItem(item: AnnouncementListEntity?, position : Int)
        fun clickItem(item: AnnouncementListEntity?, position : Int)
    }



    private val startActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.data != null && it.resultCode == Activity.RESULT_OK) {
            if (it.data!!.getStringExtra("result") == "ok") {
                //上传网站公告成功后处理刷新列表数据
                isLoadMore = false
                mViewModel.getAnnouncementManagement(isLoadMore)
            }
        }
    }

    private fun showDialog(title: String, no: String, position: Int) {
        val view = View.inflate(activity, R.layout.dialog_two_btn, null)
        val roundCornerDialog = RoundCornerDialog(
            activity, 0, 0, view, R.style.RoundCornerDialog
        )
        roundCornerDialog.show()
        roundCornerDialog.setCanceledOnTouchOutside(false) // 设置点击屏幕Dialog不消失
        //roundCornerDialog.setOnKeyListener(keylistener);//设置点击返回键Dialog不消失
        val tv_message = view.findViewById<TextView>(R.id.tv_message)
        val tv_logout_confirm = view.findViewById<TextView>(R.id.tv_logout_confirm)
        val tv_logout_cancel = view.findViewById<TextView>(R.id.tv_logout_cancel)
        tv_message.text = title

        //确定
        tv_logout_confirm.setOnClickListener { //请求接口
            mViewModel.deleteAnnouncementByNo(no, position)
            roundCornerDialog.dismiss()
        }
        //取消
        tv_logout_cancel.setOnClickListener { roundCornerDialog.dismiss() }
    }

}